'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const bannerNameList = ['红色', '橙色', '黄色', '绿色', '蓝色', '靛色', '紫色', '彩虹'];

exports.main = async (event, context) => {

	//event为客户端上传的参数
	// event = {
	// 	name: 'todayFinish',
	// 	openId: 'oplKX5NEpJs_3aAdgRiqJIFYu72M'
	// }

	let res = {};
	if (!event.openId) return;
	console.log('event : ', event)
	if (event.name == 'allInfo') {
		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();
		let nowItem = docListallList.data[0];

		// let adWatchList = nowItem.adWatchList || ['', '', ''];

		// adWatchList = adWatchList.map((adItem, adIndex) => {
		// 	if (!adItem) {
		// 		return '';
		// 	}
		// 	let today = new Date(new Date().getTime() + 8 * 60 * 60 * 1000);
		// 	let clickDay = new Date(adItem + 8 * 60 * 60 * 1000);
		// 	if ((today.getMonth() == clickDay.getMonth()) && (today.getDate() == clickDay.getDate())) {
		// 		// 今日已经看过广告
		// 		console.log('今日已经看过广告', adItem);
		// 		return adItem;
		// 	} else {
		// 		console.log('不是今天', adItem);
		// 		return '';
		// 	}
		// });
		// console.log('adWatchList', adWatchList);
		// nowItem['adWatchList'] = adWatchList;
		
		
		let allpeopleNumCount = await db.collection('userInfo').count();
		
		let  scoreNum = nowItem.scoreNum || 0;
		
		let rankCount = await db.collection('userInfo').where({
			scoreNum: dbCmd.gt(scoreNum)
		}).count();
		
		let allPeopleNum = allpeopleNumCount.total || 1;
		let rank = rankCount.total;
		
		let rate = Math.floor(((allPeopleNum - rank) / allPeopleNum) * 100);
		
		nowItem = {
			...nowItem,
			allPeople:allpeopleNumCount.total,
			rank:rankCount.total,
			des:`超越了${rate}%的用户！`
		}
		
		
		
		
		res = nowItem;
	} else if (event.name == 'finish') {

		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();

		let nowItem = docListallList.data[0];
		console.log('nowItem', nowItem);

		let correctNum = event.correctNum || 0;
		let errorNum = event.errorNum || 0;
		let scoreNum = correctNum - errorNum;
		let lastScoreNum = nowItem.scoreNum || 0;
		let isNew = false;

		if (scoreNum > lastScoreNum) {
			// 当前成绩大于历史成绩
			let needSaveItem = {
				openId: nowItem.openId,
				correctNum: correctNum,
				errorNum: errorNum,
				scoreNum: scoreNum
			};
			isNew = true;
			await saveSql(needSaveItem);
		}

		let allpeopleNumCount = await db.collection('userInfo').count();
		
		let rankCount = await db.collection('userInfo').where({
			scoreNum: dbCmd.gt(scoreNum)
		}).count();
		
		let allPeopleNum = allpeopleNumCount.total || 1;
		let rank = rankCount.total;
		
		let rate = Math.floor(((allPeopleNum - rank) / allPeopleNum) * 100);
		
		res = {
			allPeople:allpeopleNumCount.total,
			rank:rankCount.total,
			des:`超越了${rate}%的用户！`,
			isNew:isNew
		}
		

	} else if (event.name == 'getBananaAd') {
		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();

		let nowItem = docListallList.data[0];

		let adWatchList = nowItem.adWatchList || ['', '', ''];
		let startIndex = -1;

		adWatchList = adWatchList.map((adItem, adIndex) => {
			if (!adItem) {
				startIndex = adIndex;
				return '';
			}
			let today = new Date(new Date().getTime() + 8 * 60 * 60 * 1000);
			let clickDay = new Date(adItem + 8 * 60 * 60 * 1000);
			if ((today.getMonth() == clickDay.getMonth()) && (today.getDate() == clickDay.getDate())) {
				// 今日已经看过广告
				return adItem;
			} else {
				startIndex = adIndex;
				return '';
			}
		})
		if (startIndex != -1) {
			adWatchList[startIndex] = new Date().getTime();
			let needSaveItem = {
				openId: nowItem.openId
			};
			needSaveItem['baseBanana'] = nowItem.baseBanana + 8;
			needSaveItem['needAddBananaNum'] = 8;
			needSaveItem['adWatchList'] = adWatchList;
			await saveSql(needSaveItem);
			res = needSaveItem;
		} else {
			return {
				msg: '今日广告次数已用尽'
			}
		}
	} else if (event.name == 'getBanana') {
		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();

		let nowItem = docListallList.data[0];
		console.log('nowItem', nowItem);

		// res = nowItem;

		let lastGetTime = nowItem.lastGetTime;

		// 领取基础大香蕉
		let nowTime = new Date().getTime();

		let needSaveItem = {
			openId: nowItem.openId
		};

		if (nowTime - lastGetTime >= 8 * 60 * 60 * 1000) {
			// 大于等于8小时 则领取8个大香蕉 ，将lastGetTime重置为nowTime
			needSaveItem['lastGetTime'] = nowTime;
			needSaveItem['baseBanana'] = nowItem.baseBanana + 8;
			needSaveItem['needAddBananaNum'] = 8;
		} else {
			// 小于8小时，则计算能领取的大香蕉数量，并将lastGetTime增加相关的大香蕉数。
			let subTime = nowTime - lastGetTime;

			let needAddBananaNum = getBannerNum(subTime);
			if (needAddBananaNum > 0) {
				needSaveItem['lastGetTime'] = nowItem.lastGetTime + needAddBananaNum * 60 * 60 * 1000;
				needSaveItem['baseBanana'] = nowItem.baseBanana + needAddBananaNum;
				needSaveItem['needAddBananaNum'] = needAddBananaNum;
			} else {
				return {
					msg: '暂无成熟香蕉'
				}
			}

		}
		await saveSql(needSaveItem);
		res = needSaveItem;
	} else if (event.name == 'isSyn') {
		//合成大香蕉

		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();

		let nowItem = docListallList.data[0];
		console.log('nowItem', nowItem);

		let hasBanana = nowItem.baseBanana || 0;
		let bannerList = nowItem.bannerList || [];
		if (hasBanana >= 3) {
			let canSynTimes = Math.floor(hasBanana / 3); //合成大香次数
			let subBanana = hasBanana - canSynTimes * 3; //剩余大香蕉数


			let needSaveItem = {
				openId: nowItem.openId,
				baseBanana: subBanana
			};

			let failTimes = 0;
			let successTimes = new Array(8).fill(0); //存储一阶大香蕉的数组

			for (let i = 0; i < canSynTimes; i++) {
				// 计算是否合成成功;
				let succ = RandomNumBoth(0, 9);
				if (succ >= 10) {
					// 合成失败
					failTimes += 1;
				} else {
					// 合成成功
					let checkIsCaihong = RandomNumBoth(0, 100);
					if (checkIsCaihong <= 1) {
						successTimes[7] = successTimes[7] + 1; //彩虹大香蕉
						bannerList[7] = bannerList[7] + 1;
					} else {
						let nomalBanana = RandomNumBoth(0, 6);
						successTimes[nomalBanana] = successTimes[nomalBanana] + 1;
						bannerList[nomalBanana] = bannerList[nomalBanana] + 1;
					}
				}
			}

			needSaveItem['bannerList'] = bannerList;
			needSaveItem['baseBanana'] = needSaveItem['baseBanana'] + failTimes;

			await saveSql(needSaveItem);

			return {
				successTimes: successTimes,
				failTimes: failTimes
			}

		} else {
			return {
				msg: '基础大香蕉不足！'
			}
		}
	} else if (event.name == 'isSell') {
		//出售大香蕉

		const collectionallList = db.collection('userInfo');
		const docListallList = await collectionallList.where({
			openId: event['openId']
		}).get();

		let nowItem = docListallList.data[0];
		console.log('nowItem', nowItem);

		let bannerList = nowItem.bannerList || [];
		let sellIndex = event.sellIndex;

		let sellMoney = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 1];
		let saleNum = bannerList[sellIndex] || 0;


		if (saleNum > 0) {
			// 开始卖香蕉
			let myId = JSON.parse(JSON.stringify(nowItem['_id']));
			let balanceAdd = sellMoney[sellIndex] * saleNum; //售卖所得的全部宝石

			let needSaveItem = {
				openId: nowItem.openId
			};
			needSaveItem['balanceTotal'] = Number(nowItem.balanceTotal) + Number(balanceAdd);
			bannerList[sellIndex] = 0;

			needSaveItem['bannerList'] = bannerList;

			await saveSql(needSaveItem);

			await db.collection('balanceList').add({
				openId: event['openId'],
				type: `出售${bannerNameList[sellIndex]}大香蕉*${saleNum}`,
				balanceTotal: needSaveItem['balanceTotal'],
				balanceAdd: balanceAdd,
				createTime: new Date().getTime(),
				updateTime: new Date().getTime()
			});

			if (nowItem.inviteId) {
				// 存在邀请人 则邀请人获得奖励
				console.log('存在邀请人 则邀请人获得奖励');
				let addNum = balanceAdd * 0.3;
				let incRes = await db.collection('userInfo').doc(nowItem.inviteId).update({
					balanceTotal: db.command.inc(addNum)
				});
				console.log('incRes', incRes);
				// 好友贡献列表
				let gongxianRes = await db.collection('friendList').where({
					myId: myId
				}).updateAndReturn({
					giveBalance: db.command.inc(addNum)
				});
				console.log('gongxianRes', gongxianRes);

				let inviteInfo = await db.collection('userInfo').where({
					_id: nowItem.inviteId
				}).get();
				console.log('inviteInfo', inviteInfo);

				if (inviteInfo && inviteInfo.data && inviteInfo.data.length > 0) {
					inviteInfo = inviteInfo.data[0];
					await db.collection('balanceList').add({
						openId: inviteInfo.openId,
						type: `好友${myId.slice(0,6)}出售${bannerNameList[sellIndex]}大香蕉*${saleNum}`,
						balanceTotal: inviteInfo['balanceTotal'],
						balanceAdd: addNum,
						createTime: new Date().getTime(),
						updateTime: new Date().getTime()
					});
				}
			}
			return {
				balanceAdd: balanceAdd
			}

		} else {
			return {
				msg: '出售的大香蕉不足！'
			}
		}



	}
	//返回数据给客户端
	return res;
};


function RandomNumBoth(Min, Max) {
	var Range = Max - Min;
	var Rand = Math.random();
	var num = Min + Math.round(Rand * Range); //四舍五入
	return num;
}

function getBannerNum(subTime) {
	let theTime = parseInt(subTime / 1000); // 秒
	let middle = 0; // 分
	let hour = 0; // 小时
	if (theTime <= 0) theTime = 0;

	if (theTime >= 60) {
		middle = parseInt(theTime / 60);
		theTime = parseInt(theTime % 60);
		if (middle >= 60) {
			hour = parseInt(middle / 60);
			middle = parseInt(middle % 60);
		}
	}
	return hour;
}



function RandomNumBoth(Min, Max) {
	var Range = Max - Min;
	var Rand = Math.random();
	var num = Min + Math.round(Rand * Range); //四舍五入
	return num;
}



async function saveSqlAd(findItem) {
	const collectionallList = db.collection('adWatchList');
	let tempItem = JSON.parse(JSON.stringify(findItem));
	await collectionallList.add({
		...tempItem,
		updateTime: new Date().getTime()
	});
}

async function saveSql(findItem) {
	const collectionallList = db.collection('userInfo');
	let tempItem = JSON.parse(JSON.stringify(findItem));
	const docListallList = await collectionallList.where({
		openId: tempItem['openId']
	}).get();
	if (!docListallList.data || docListallList.data.length === 0) {
		console.log('存入今日列表');
		// await collectionallList.add({
		// 	...tempItem,
		// 	updateTime: new Date().getTime(),
		// 	dayHasFinish:'',
		// 	allFinishTime:0
		// });
	} else {
		console.log('内容已存在');
		tempItem['updateTime'] = new Date().getTime();
		await collectionallList.doc(docListallList.data[0]._id).update(tempItem);
	}
}